package com.fastplatform.specification;

import com.fastplatform.entity.Role;
import com.fastplatform.entity.Role_;
import org.springframework.data.jpa.domain.Specification;
import jakarta.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

public class RoleSpecification {
    
    /**
     * 根据条件查找角色列表（使用JPA Criteria Queries和元数据）
     */
    public static Specification<Role> findRolesByConditions(String roleName, String roleCode, Integer status) {
        return (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            
            // 基础条件：未删除
            predicates.add(criteriaBuilder.equal(root.get(Role_.deleted), false));
            
            // 角色名称模糊查询
            if (roleName != null && !roleName.trim().isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get(Role_.roleName), "%" + roleName + "%"));
            }
            
            // 角色编码模糊查询
            if (roleCode != null && !roleCode.trim().isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get(Role_.roleCode), "%" + roleCode + "%"));
            }
            
            // 状态精确查询
            if (status != null) {
                predicates.add(criteriaBuilder.equal(root.get(Role_.status), status));
            }
            
            // 排序
            query.orderBy(criteriaBuilder.asc(root.get(Role_.sortOrder)));
            
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };
    }
}